function ecogTopoplot(X,Y,dat,Anat,range)

% ecogTopoplot(X,Y,dat,Anat)
% shows an recon image and overlays data
% INPUT: X,Y vectors of coordinates coregistered to the image Anat (use ginput)
%        Anat: the image (use imread)
%        dat: the data to visualize. data are automatically scaled to
%        range: two element interval which defines smallest and biggest
%        value
%        min=blue, max=red

if nargin <5,
    range=[min(dat),max(dat)];
end
% triangulate grid electrodes
TRI = delaunay(X,Y);

F=figure;
% initialize color and alpha map
c=colormap(jet);
alp=alphamap('vdown');%('rampup');
% alpha=0.5;

% show the image (requires image processing toolbox)
imshow(Anat);

% reorganize data triangulated data
xCoord=zeros(3,size(TRI,1));
yCoord=zeros(3,size(TRI,1));
colLow=zeros(3,size(TRI,1),3);
alpLow=zeros(3,size(TRI,1));

for k=1:size(TRI,1),
    xCoord(:,k)=round([X(TRI(k,1));X(TRI(k,2));X(TRI(k,3))]);
    yCoord(:,k)=round([Y(TRI(k,1));Y(TRI(k,2));Y(TRI(k,3))]);
end

% determine color range
cLow=round((dat-range(1))./diff(range)*63)+1;

% each node gets its color 
for k=1:size(TRI,1),
   colLow(:,k,:)=permute([c(cLow(TRI(k,1)),:);c(cLow(TRI(k,2)),:);c(cLow(TRI(k,3)),:)],[1 3 2]);
   alpLow(:,k)=[alp(cLow(TRI(k,1)));alp(cLow(TRI(k,2)));alp(cLow(TRI(k,3)))];
end
% plot the patches
pH1=patch(xCoord,yCoord,colLow,'FaceVertexAlphaData',reshape(alpLow,numel(alpLow),1),'FaceAlpha','interp');
shading flat
shading interp
